<script setup lang="ts">
import {
  confirmReceiptAPI,
  deleteOrderAPI,
  getOrderListAPI,
  getWeMiniPayOrMockAPI,
} from '@/services/order'
import type { OrderItem } from '@/types/order'
import { onMounted, ref } from 'vue'
import { OrderState, orderStateList } from '@/services/constants'
// @ts-ignore
import { throttle, debounce } from 'lodash'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
// 接收父组件传递的订单数据
const props = defineProps<{
  // 当前页面订单类型
  orderState: number
}>()
// 当前页码
let currPage = ref(0)
// 总页码
let totalPages = ref(1)
// 一页每次加载的数据
let pageSize = ref(2)
// 订单列表数据
const orderList = ref<OrderItem[]>([])
// 底部加载提示文字
let loadingText = ref('正在加载...')
// 控制 scroll-view 刷新
let refreshTrigger = ref(false)

// 获取订单列表数据(上拉获取更多)
const getOrderList = throttle(async () => {
  uni.showLoading()
  // 判断是否有下一页数据
  if (!(currPage.value < totalPages.value))
    return (loadingText.value = '没有更多数据~')
  // 继续获取数据更新页码并拼接商品列表数据
  const result = await getOrderListAPI({
    page: currPage.value + 1,
    pageSize: pageSize.value,
    orderState: props.orderState,
  })
  orderList.value = orderList.value.concat(result.result.items)
  currPage.value = result.result.page
  totalPages.value = result.result.pages
  uni.hideLoading()
}, 2000)
// 下拉刷新
const onRefresh = debounce(async () => {
  refreshTrigger.value = true
  // 清空订单列表数据
  orderList.value = []
  // 重新获取第一页数据
  currPage.value = 0
  await getOrderList()
  // 关闭刷新提示框
  refreshTrigger.value = false
}, 500)
// 删除订单
const onDeleteOrder = throttle(async (orderId: string) => {
  // 二次确认弹窗
  const { confirm } = await uni.showModal({
    title: '删除订单',
    content: '确定删除该订单吗？',
  })
  if (confirm) {
    // 发请求删除订单
    await deleteOrderAPI({ ids: [orderId] })
    uni.showToast({ title: '删除成功', icon: 'none' })
    // 删除前端数据
    orderList.value = orderList.value.filter((item) => item.id !== orderId)
  }
}, 2000)
// 订单支付
const onOrderPay = throttle(async (item: OrderItem) => {
  // 判断订单是否超时
  if (item.countdown < 0) {
    uni.showToast({ title: '订单已超时不可支付', icon: 'none' })
    // 修改订单状态
    item.orderState = OrderState.YiQuXiao
    return
  }
  // 调用支付的接口方法
  const result = await getWeMiniPayOrMockAPI(item.id)
  if (import.meta.env.PROD) {
    // #ifdef MP-WEIXIN
    // 发起微信支付
    wx.requestPayment(result.result as WechatMiniprogram.RequestPaymentOption)
    // #endif
  }
  // 支付成功提示
  uni.showToast({ title: '支付成功', icon: 'success' })
  // 更新状态
  item.orderState = OrderState.DaiFaHuo
}, 2000)
// 确认收货
const onConfirmReceipt = throttle(async (item: OrderItem) => {
  // 二次确认弹窗
  const { confirm } = await uni.showModal({
    title: '确认收货',
    content: '为保障您的权益，请收到货并确认无误后，再确认收货',
  })
  // 如果确认
  if (confirm) {
    uni.showToast({ title: '确认收货成功', icon: 'success' })
    // 发请求确认收货 待收货 -> 待评价
    const result = await confirmReceiptAPI(item.id)
    // 更新订单状态
    item.orderState = OrderState.YiWanCheng
  }
}, 2000)

// 组件使用Vue的生命周期函数
onMounted(async () => {
  // 获取当前订单分类的数据
  await getOrderList()
})
</script>
<template>
  <scroll-view
    scroll-y
    class="orders"
    @scrolltolower="getOrderList"
    refresher-enabled
    refresher-default-style="white"
    refresher-background="#eee"
    :refresher-triggered="refreshTrigger"
    @refresherrefresh="onRefresh"
  >
    <view class="card" v-for="item in orderList" :key="item.id">
      <!-- 订单信息 -->
      <view class="status">
        <text class="date">{{ item.createTime }}</text>
        <!-- 订单状态文字 -->
        <text>{{ orderStateList[item.orderState].text }}</text>
        <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
        <text
          v-if="[4, 5, 6].includes(item.orderState)"
          @tap="onDeleteOrder(item.id)"
          class="icon-delete"
        ></text>
      </view>
      <!-- 商品信息，点击商品跳转到订单详情(传递订单id)，不是商品详情 -->
      <navigator
        v-for="sku in item.skus"
        :key="sku.id"
        class="goods"
        :url="`/pagesOrder/detail/detail?id=${item.id}`"
        hover-class="none"
      >
        <view class="cover">
          <image class="image" mode="aspectFit" :src="sku.image"></image>
        </view>
        <view class="meta">
          <view class="name ellipsis">{{ sku.name }}</view>
          <view class="type">{{ sku.attrsText }}</view>
        </view>
      </navigator>
      <!-- 支付信息 -->
      <view class="payment">
        <text class="quantity">共{{ item.totalNum }}件商品</text>
        <text>实付</text>
        <text class="amount">
          <text class="symbol">¥</text>{{ item.totalMoney }}</text
        >
      </view>
      <!-- 订单操作按钮 -->
      <view class="action">
        <!-- 待付款状态：显示去支付按钮 -->
        <template v-if="item.orderState === 1">
          <view class="button primary" @tap="onOrderPay(item)">去支付</view>
        </template>
        <template v-else>
          <navigator
            class="button secondary"
            :url="`/pagesOrder/create/create?orderId=${item.id}`"
            hover-class="none"
          >
            再次购买
          </navigator>
          <!-- 待收货状态: 展示确认收货 -->
          <view
            v-if="item.orderState === 3"
            @tap="onConfirmReceipt(item)"
            class="button primary"
            >确认收货</view
          >
        </template>
      </view>
    </view>
    <!-- 底部提示文字 -->
    <view
      class="loading-text"
      :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }"
    >
      {{ loadingText }}
    </view>
  </scroll-view>
</template>

<style lang="scss">
.orders {
  .card {
    min-height: 100rpx;
    padding: 20rpx;
    margin: 20rpx 20rpx 0;
    border-radius: 10rpx;
    background-color: #fff;
    &:last-child {
      padding-bottom: 40rpx;
    }
  }
  .status {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #999;
    margin-bottom: 15rpx;
    .date {
      color: #666;
      flex: 1;
    }
    .primary {
      color: #ff9240;
    }
    .icon-delete {
      line-height: 1;
      margin-left: 10rpx;
      padding-left: 10rpx;
      border-left: 1rpx solid #e3e3e3;
    }
  }
  .goods {
    display: flex;
    margin-bottom: 20rpx;
    .cover {
      width: 170rpx;
      height: 170rpx;
      margin-right: 20rpx;
      border-radius: 10rpx;
      overflow: hidden;
      position: relative;
      .image {
        width: 100%;
        height: 100%;
      }
    }
    .quantity {
      position: absolute;
      bottom: 0;
      right: 0;
      line-height: 1;
      padding: 6rpx 4rpx 6rpx 8rpx;
      font-size: 24rpx;
      color: #fff;
      border-radius: 10rpx 0 0 0;
      background-color: rgba(0, 0, 0, 0.6);
    }
    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }
    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }
    .type {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 10rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }
    .more {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 22rpx;
      color: #333;
    }
  }
  .payment {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    line-height: 1;
    padding: 20rpx 0;
    text-align: right;
    color: #999;
    font-size: 28rpx;
    border-bottom: 1rpx solid #eee;
    .quantity {
      font-size: 24rpx;
      margin-right: 16rpx;
    }
    .amount {
      color: #444;
      margin-left: 6rpx;
    }
    .symbol {
      font-size: 20rpx;
    }
  }
  .action {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 20rpx;
    .button {
      width: 180rpx;
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 20rpx;
      border-radius: 60rpx;
      border: 1rpx solid #ccc;
      font-size: 26rpx;
      color: #444;
    }
    .secondary {
      color: #27ba9b;
      border-color: #27ba9b;
    }
    .primary {
      color: #fff;
      background-color: #27ba9b;
    }
  }
  .loading-text {
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
  }
}
</style>
